let items = document.querySelectorAll(".item");
let boxs = document.querySelectorAll(".box");
let isDragging = false;
let offsetX, offsetY;
let chosen = -1;
let can = 0;
items.forEach((item, idx) => {
  let left = 520 + 170 * idx;
  items[idx].style.left = left + "px";
  items[idx].style.top = "420px";
  boxs[idx].style.left = left + "px";
  boxs[idx].style.top = "420px";
});
items.forEach((item, idx) => {
  items[idx].addEventListener("mousedown", (event) => {
    event.preventDefault && event.preventDefault();
    if (idx !== can) return;
    isDragging = true;
    offsetX = event.offsetX;
    offsetY = event.offsetY;
    chosen = idx;
    items[idx].style.zIndex = 5;
    items[idx].style.cursor = "grabbing";
    // addZ();
  });
});

document.addEventListener("mousemove", function (event) {
  console.log(can);
  if (isDragging) {
    const x = event.clientX - offsetX;
    const y = event.clientY - offsetY;
    items[chosen].style.left = `${x}px`;
    items[chosen].style.top = `${y}px`;
    boxs.forEach((box, idx) => {
      let rect = box.getBoundingClientRect();
      let x = event.clientX;
      let y = event.clientY;
      if (
        x >= rect.left &&
        x <= rect.right &&
        y >= rect.top &&
        y <= rect.bottom
      ) {
        if (idx === chosen) {
          box.style.backgroundColor = "black";
          box.style.border = "3px dashed white";
        } else {
          items[idx].style.backgroundColor = "black";
          items[idx].style.border = "3px dashed white";
        }
      } else {
        if (idx === chosen) {
          box.style.backgroundColor = "white";
          box.style.border = "3px solid black";
        } else {
          items[idx].style.backgroundColor = "white";
          items[idx].style.border = "3px solid black";
        }
      }
    });
  }
});

document.addEventListener("mouseup", function () {
  if (!isDragging) return;
  console.log(1);
  isDragging = false;
  if (chosen === -1) return;
  if (chosen != -1) {
    let left = 520 + 170 * chosen;
    items[chosen].style.left = left + "px";
    items[chosen].style.top = "420px";
  }
  items.forEach((item, idx) => {
    items[idx].style.backgroundColor = "white";
    items[idx].style.border = "3px solid black";
    items[idx].style.zIndex = 1;
  });
  boxs.forEach((box, idx) => {
    let rect = box.getBoundingClientRect();
    let x = event.clientX;
    let y = event.clientY;
    if (
      x >= rect.left &&
      x <= rect.right &&
      y >= rect.top &&
      y <= rect.bottom
    ) {
      can = idx;
    }
  });
  //   minusZ();
});
